import knex from '../connection'
import type { ITransaction } from '../define/transaction'
import type { Data } from '../define/types'

class Transaction implements ITransaction {
  async runInTransaction(callback: (trx: any) => Data) {
    return await knex.transaction(async (trx: any) => {
      try {
        const result = await callback(trx)
        await trx.commit()
        return result
      } catch (error: any) {
        console.error(error.message)
        await trx.rollback()
        throw error
      }
    })
  }
}

export default new Transaction()
